<template>
  <div>
    <div :id="code" />
    <!-- 添加打印对话框 -->
    <a-modal :visible="visible" @ok="visible=false" @cancel="visible=false" centered>
      <div slot="title">打印</div>
      <a-form-model :label-col="{ span: 10 }">
        <a-form-model-item label="申请标签数量 (个)">
          <span class="numStyle">{{ labelPrintData.applyNumber }}</span>
        </a-form-model-item>
        <a-form-model-item label="已打印标签数量 (个)">
          <span class="numStyle">{{ labelPrintData.printedNumber || 0 }}</span>
        </a-form-model-item>
        <a-form-model-item label="本次打印标签数量 (个)">
          <a-button
            @click="wantToPrintNum--"
            :disabled="wantToPrintNum == 0"
          >-</a-button>
          <span class="numStyle">{{wantToPrintNum}}</span>
          <a-button
            @click="wantToPrintNum++"
            :disabled="wantToPrintNum == labelPrintData.applyNumber - labelPrintData.printedNumber"
          >+</a-button>
        </a-form-model-item>
      </a-form-model>
      <div
        slot="footer"
        style="display:flex;justify-content: center;"
      >
        <a-button @click="visible=false">取消</a-button>
        <a-button
          type="primary"
          @click="printLableHandle"
        >提交</a-button>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { request } from "@/utils/request";
import { printLable } from "@/services/user";
import { getLodop } from "@/utils/LodopFuncs";
import checkPermission from "../../utils/permission";
import axios from "axios";

export default {
  name: "AmisPage",
  data() {
    return {
      baseURL: process.env.VUE_APP_SUYUAN_URL,
      amisScoped: null,
      // 打印功能对话框显隐控制
      visible: false,
      // 本次印标签个数
      wantToPrintNum: 0,
      // 打印对话框详情数据 1.申请总数 2.已打印数目 3.id
      // 请求打印携带路径参数id,本次打印数目
      labelPrintData: {},
    };
  },
  computed: {
    code() {
      return this.$route.meta.amis;
    },
    userInfo() {
      return this.$store.getters["account/user"];
    },
  },
  watch: {
    code() {
      this.init();
    },
  },
  // 添加created,注册window全局函数,在labelPrintManage.json(打印功能)文件中调用
  created() {
    window.showMessageTest = (data) => {
      this.labelPrintData = data;
      this.visible = true;
    };
  },
  methods: {
    init() {
      let vm = this;
      if (this.amisScoped) {
        this.amisScoped.unmount();
      }
      this.$nextTick(() => {
        // "@/assets/json/" + this.code + ".json"
        if(!this.code){
          return false
        }
        let path = `${process.env.BASE_URL}json/${this.code}.json`
        axios.get(path).then(res=>{
          let amisJSON = res.data
          this.permission(amisJSON);
          this.amisScoped = this.$amis.embed(
              "#" + this.code,
              amisJSON,
              {
                data: {
                  myData: 1,
                      addBtn: "新增",
                      detailBtn: "查看",
                      deleteBtn: "删除",
                      editBtn: "编辑",
                      enableBtn: "启用/禁用",
                      exportBtn: "导出",
                      loginUserId:this.userInfo.loginUserId,
                      userInfoName:this.userInfo.name,
                      traceabilityAddressUrl:process.env.VUE_APP_TRACEABILITY_ADDRESS_URL
                },
              },
              {
                // 可以不传，用来实现 ajax 请求
                fetcher: ({ url, method, data, config }) => {
                  console.log(url, method,)
                  if (!data) {
                    data = {};
                  }
                  data["tenantCode"] = sessionStorage.getItem("tenantCode");
                  data["subjectInfoId"] = sessionStorage.getItem("subjectInfoId");
                  data["loginUserId"] = this.userInfo.loginUserId;
                  return request(url, method, data, config);
                },
                jumpTo: (to) => {
                  if (to === "/amis/agriVarietyManagementManage") {
                    vm.$router.push({
                      path: "/amis/agriVarietyManagementManage",
                    });
                  }
                },
                theme: "antd",
              }
          );
          // this.amisScoped.updateProps({
          //   data: {
          //     addBtn: "新增",
          //     detailBtn: "查看",
          //     deleteBtn: "删除",
          //     editBtn: "编辑",
          //     enableBtn: "启用/禁用",
          //   },
          // });
        })
      });
    },
    // 打印对话框,点击提交打印响应函数
    printLableHandle() {
      printLable(this.labelPrintData.id, this.wantToPrintNum).then((res) => {
        if (this.wantToPrintNum > 0) {
          let status = res.data.status;
          let msg = res.data.msg;
          if (status === 0) {
            // this.$message.success("操作成功");
            //开始调用打印机进行打印s
            this.visible = false;
            this.wantToPrintNum = 0;
            let dataList = res.data.data.rows;
            dataList.forEach((item) => {
              this.printHandle(item);
            });
            this.init();
          } else {
            this.$message.success(msg);
          }
        } else {
          this.$message.success("打印标签数量需大于0");
        }
      });
    },
    printHandle(labelNo) {
      let vm = this
      const LODOP = getLodop(null, null, vm);
      if (LODOP) {
        const iPrinterCount = LODOP.GET_PRINTER_COUNT(); // 判断打印是否有打印机
        if (iPrinterCount == 0) {
          this.$message.error("当前没有可使用的打印机，请安装打印机！");
          return false;
        }
        LODOP.PRINT_INITA("-19.37mm", "-25.72mm", "180mm", "180mm", "陇县奶山羊大数据");
        LODOP.SET_PRINT_PAGESIZE(1, 500, 300, "CreateCustomPage");
        LODOP.SET_PRINT_MODE("PRINT_NOCOLLATE", 1);
        LODOP.ADD_PRINT_BARCODE(
          "23.34mm",
          "55.14mm",
          "23.52mm",
          "23.52mm",
          "QRCode",
          this.baseURL + labelNo
        );
        LODOP.ADD_PRINT_TEXT("23.57mm", "74.61mm", "43.92mm", "7.2mm", labelNo);
        LODOP.SET_PRINT_STYLEA(0, "FontName", "微软雅黑");
        LODOP.SET_PRINT_STYLEA(0, "FontSize", 7);
        LODOP.SET_PRINT_STYLEA(0, "Bold", 1);
        LODOP.SET_PRINT_STYLEA(0, "Angle", 180);

        // LODOP.PRINT_DESIGN() // 最后一个打印(或预览、维护、设计)语句
        LODOP.PRINT();
      }
    },
    permission(data) {
      for (let key in data) {
        if (typeof data[key] === "object") {
          if (Array.isArray(data[key])) {
            for (let i = 0; i < data[key].length; i++) {
              this.permission(data[key][i]);
            }
          } else {
            this.permission(data[key]);
          }
        } else {
           if (data["permission"]) {
             data["className"] = !checkPermission(this.code, data["permission"])
               ? "no-permission"
               : "";
           }
        }
      }
    },
    gotoPage (data,code) {
      this.$router.push({
        path: code,
        query:{
          subjectInfoId: data.subjectInfoId
        }
      })
    }
  },
  mounted() {
    this.init();
    let vm = this
    window.gotoPage = function (data,code){
      vm.gotoPage(data,code)
    }
  },
  destroyed() {
    console.log("==================");
    this.amisScoped.unmount();
  },
};
</script>

<style lang="less">
.numStyle {
  margin: 0 30px;
}
.no-permission {
  display: none !important;
}
.vm--modal {
  padding: 20px;
  height: 150px !important;
  a {
    color: #FF003F;
    // text-decoration-line:;
  }

}
</style>
